

var fs = require('fs');
var path = require('path');
var uuid = require('./../public/uuid');
var file_util = require('./../public/file_util');
const checkList = ['.prefab', '.fire', '.scene']
var cur_path = process.cwd();
//资源目录
var res_path = process.argv[2]
//导出的语言文本拷贝到哪里
var copy_path = process.argv[3]
//是否导出预制体文件
var isWritePrefab = process.argv[4];
//是否读取之前的文本
var readTemplate = process.argv[5]
var out_file_name = 'ui_text_zh'
var outData = {
    isEncode: 0,
    data: {
        data: {},
        type: 2,
        name: out_file_name
    }
}

var template_path = path.join(cur_path, path.sep, outData.data.name + '.json')


let LangTextView = '9ad68LGPj9ErIHsCO5TFH3S'
let GameTextView = '6cc0c1vWa1PS7musicrU0Mj'

var allData = {}
var tempData = {}
var LangTextComp = {
    "__type__": "9ad68LGPj9ErIHsCO5TFH3S",
    "_name": "",
    "_objFlags": 0,
    "__editorExtras__": {},
    "node": {
        "__id__": 45
    },
    "_enabled": true,
    "__prefab": {
        "__id__": 51
    },
    "textId": "DelAdButton_MingCheng",
    "_id": ""
}
var CompPrefabInfo = {
    "__type__": "cc.CompPrefabInfo",
    "fileId": "69XHjl0I1M1q+H0NbWIG46"
}
//如果有原来的文件，可以将原来的文件作为参考文件
if (readTemplate && file_util.existsSync(template_path)) {
    let data = file_util.readFile(template_path)
    if (data) {
        outData = JSON.parse(data)
        for (const key in outData) {
            if (Object.prototype.hasOwnProperty.call(outData, key)) {
                const element = outData[key];
                tempData[element] = key;
            }
        }
    }
}

function hasLangTextView(obj, jsonList, compId) {
    let node = jsonList[obj.node.__id__]
    let _components = node._components;
    for (let index = 0; index < _components.length; index++) {
        const element = _components[index];
        let id = element.__id__;
        let comp = jsonList[id]
        if (comp.__type__ == compId) {
            return comp;
        }
    }
    return null;
}

function addLangTextView(obj, jsonList, textId) {
    let node = jsonList[obj.node.__id__]
    let data = JSON.parse(JSON.stringify(LangTextComp))
    let id = jsonList.length;
    node._components.push({ __id__: id })
    data.__id__ = id;
    data.node.__id__ = obj.node.__id__;
    data.textId = textId;
    jsonList.push(data)
    let prefabId = jsonList.length
    data.__prefab.__id__ = prefabId;
    let prefab = JSON.parse(JSON.stringify(CompPrefabInfo))
    prefab.fileId = uuid.uuid();
    jsonList.push(prefab)

}

function containsChinese(str) {
    // 使用正则表达式匹配中文字符
    return /[\u4e00-\u9fff\u3400-\u4dbf\uf900-\ufaff]/.test(str);
}
//解析整个目录
function parseAllRes(res_path) {
    // console.log(" res_path ", res_path)
    var stat = fs.statSync(res_path);
    if (!stat.isDirectory()) {
        return;
    }
    var subpaths = fs.readdirSync(res_path),
        subpath;
    for (var i = 0; i < subpaths.length; ++i) {
        if (subpaths[i][0] === '.') {
            continue;
        }
        subpath = path.join(res_path, subpaths[i])//  + '/' + ;
        stat = fs.statSync(subpath);
        if (stat.isFile()) {
            parseRes(subpath)
        }
        else if (stat.isDirectory()) {
            // var temp = subpath.replace(res_path, '')
            parseAllRes(subpath)
        }
    }
}

function parseRes(res_path) {
    // console.log(' res_path ', res_path)
    let extname = path.extname(res_path);
    let index = checkList.indexOf(extname)

    if (index >= 0) {
        console.log(' index ', index)
        let baseName = path.basename(res_path, extname);
        console.log(' baseName ', baseName)
        let fileData = file_util.readFile(res_path)
        if (fileData) {
            var jsonList = JSON.parse(fileData);
            if (baseName == 'DelAdButton') {

                console.log(' jsonList 51 ', jsonList[51])
            }
            for (var i = 0; i < jsonList.length; i++) {
                let obj = jsonList[i]
                let node = null;
                switch (obj.__type__) {
                    case 'cc.Label':
                        node = jsonList[obj.node.__id__]
                        if (node) {


                            let text = obj._string;
                            console.log(' text ', text)
                            if (containsChinese(text)) {
                                let key = tempData[text]
                                if (!key) {
                                    // let labelName = baseName + '_' + node._name
                                    key = uuid.uuid()
                                    tempData[text] = key
                                    outData.data.data[key] = text
                                }

                                if (!hasLangTextView(obj, jsonList, GameTextView)) {
                                    let langTextComp = hasLangTextView(obj, jsonList, LangTextView)
                                    if (langTextComp) {
                                        langTextComp.textId = key;
                                    } else {
                                        addLangTextView(obj, jsonList, key)
                                    }
                                }

                                let data = allData[baseName]
                                if (!data) {
                                    data = {}
                                    data.path = res_path
                                    allData[baseName] = data;
                                }
                                data[node._name] = text;

                            }
                        }
                        break;
                    case 'cc.RichText':
                        break;
                    default:
                        break;
                }
            }
            if (isWritePrefab == 1) {
                file_util.writeFile(res_path, JSON.stringify(jsonList, null, 2))
            }

        }
    }
}

function main(res_path, out_path) {
    parseAllRes(res_path)
    console.log(' outData ', outData)
    file_util.writeFile(path.join(out_path, path.sep, 'ui_all_zh.json'), JSON.stringify(allData, null, 2))
    file_util.writeFile(path.join(out_path, path.sep, out_file_name + '.json'), JSON.stringify(outData, null, 2))
    if (copy_path) {
        file_util.writeFile(path.join(copy_path, path.sep, out_file_name + '.json'), JSON.stringify(outData, null, 2))
    }
}

if (res_path) {
    main(res_path, cur_path)
}